//== SAGITTARIUS ============================================================================

//== BEGINNING OF CODE ===============================================================

#include "sagittarius/core/SagittariusCore.h"
#include "sagittarius/builtins/modules/io.h"
#include "sagittarius/io/io.h"
#include <string.h>
#include <malloc.h>

sg_value* sg_mod_io_fprintln(void* ctx, sg_value* sv) {
    SG_WRITE(2, "sg_mod_io_fprintln\n");
    // cast
    sg_str_val* str = sg_cast_str(sv);
    // perform
    LX_WRITE_BUFL(1, str->w, str->n);
    SG_WRITE(1, "\n");
    return NULL;
}

void sg_load_mod_io(sg_value* vmod) {
    //sg_mod_io_members members;
    
    SG_WRITE(2, "Loading module io\n");
    AT(vmod->t == (sg_type*)sg_global_session()->bt->mod, "Wrong type for module");
    
    symcode s_println = symtab_get_or_insert_cstr(sg_global_session()->st, "println");
    
    sg_fun_val* f_println=sg_create_fun();
    // symbol
    f_println->s = s_println;
    // fptr
    f_println->f = (void*)(sg_mod_io_fprintln);
    // nargs
    f_println->nargs = 1;
    //members.f_println = f_println;
    
    // create field for "println"
    sg_value** ppval = bf_do_faccessl(vmod, s_println);
    *ppval = (sg_value*)f_println;
    
    //sg_module* mod=sg_cast_module(vmod);
    //sg_mod_io_generate(mod, &members);
}

void sg_unload_mod_io(sg_value* mod) {
    SG_WRITE(2, "Unloading module io\n");
}

void sg_register_mod_io(sg_session* s) {
    //sg_session* s = sg_global_session();
    sg_module* m=sg_create_module(s);
    // symbol "io"
    m->s = symtab_get_or_insert_cstr(s->st, "io");
    
    m->load_mod = sg_load_mod_io;
    sg_register_mod(s->ml, m);
}
